﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Objects;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Entity;

namespace CSP.BL
{
    public static class RoleHelper
    {

        public static void OnRoleDisabling(int roleID)
        {
            using (var dc = new Entity.CSPEntities())
            {
                dc.Roles.First(p => p.RoleID == roleID).Disabled = true;
                dc.SaveChanges();
            }
        }

        public static void OnRoleInserting(ObjectContext dc, Role role, string countryList, string pageList, string belongsTo)
        {
            if (belongsTo != null)
            {
                role.BelongsTo = belongsTo;
            }

            if (countryList != null)
            {
                var countries = dc.CreateQuery<Entity.Country>("[Countries]");
                foreach (var country in countryList.Split(','))
                {
                    int countryID = int.Parse(country);
                    var entity = countries.First(p => p.CountryID == countryID);
                    role.Countries.Add(entity);
                }
            }

            if (pageList != null)
            {
                var pages = dc.CreateQuery<Entity.AspxPage>("[AspxPages]");
                foreach (var page in pageList.Split(','))
                {
                    int pageID = int.Parse(page);
                    var entity = pages.First(p => p.PageID == pageID);
                    role.AspxPages.Add(entity);
                }
            }
        }


        public static void OnRoleUpdating(ObjectContext dc, Role role, string countryList, string pageList, string belongsTo)
        {
            role.Countries.Load();
            role.Countries.Clear();

            role.AspxPages.Load();
            role.AspxPages.Clear();

            OnRoleInserting(dc, role, countryList, pageList, belongsTo);
        }
    }
}
